<?php

namespace App\Jobs\Bureau;

use App\Models\Bureau\WxBureau;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;

class BureauGeoCodeRegeoJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $bureau_id = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($bureau_id)
    {
        $this->bureau_id = $bureau_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if(_empty_($this->bureau_id)){
            return;
        }
        $bureau = WxBureau::find($this->bureau_id);
        $longitude = $bureau->longitude;
        $latitude = $bureau->latitude;

        if(_empty_($longitude) || _empty_($latitude)){
            return;
        }

        $web_key = Settings::get('app_gaode_web_server_key', '');
        $url = 'https://restapi.amap.com/v3/geocode/regeo?key='.$web_key.'&radius=1000'.'&location='.$longitude.','.$latitude;
        $post = Http::get($url);
        if($post->successful()){
            $res = $post->json();
            if($res['status'] == 0){
                _logger_(__file__, __line__, $res['info']);
                return ;
            }else if($res['status'] == 1){
                if(_array_key($res['regeocode'], 'addressComponent', [])){
                    $city = $res['regeocode']['addressComponent']['city'];
                    $province = $res['regeocode']['addressComponent']['province'];
                    $district = $res['regeocode']['addressComponent']['district'];
                    $country = $res['regeocode']['addressComponent']['country'];
                    if(_empty_($city)){
                        if($province){
                            $city = $province;
                        }
                    }
                    WxBureau::where('id', $this->bureau_id)->update([
                        'country' => $country,
                        'province' => $province,
                        'city' => $city,
                        'district' => $district
                    ]);
                }
            }
        }else{
            _logger_(__file__, __line__, '服务端api请求出错');
        }

    }
}
